package com.zyw.security.shiro.web.realm;

import com.zyw.security.shiro.web.authc.AuthInfo;
import com.zyw.security.shiro.web.authc.AuthService;
import com.zyw.security.shiro.web.authc.tk.FormAuthcToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.jdbc.JdbcRealm;

/**
 * 用户名密码登录
 *
 * @author zhangyw
 * @date 2018/1/5 16:08
 * @see JdbcRealm
 */
public class FormAuthRealm extends BasicAuthRealm {

    public FormAuthRealm() {
        this.setName("sky_sso_username_password_realm");
        this.setAuthenticationTokenClass(FormAuthcToken.class);
    }

    public FormAuthRealm(AuthService authService) {
        this();
        this.setAuthService(authService);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        FormAuthcToken authcToken = (FormAuthcToken) token;
        String username = authcToken.getUsername();
        String password = authcToken.getPassword();

        AuthInfo authInfo = getAuthService().getAuthInfo(username);

        if (authInfo == null) {
            throw new UnknownAccountException("账户不存在");
        }

        if (!getAuthService().validCredentials(username, password, authInfo.getPassword())) {
            throw new IncorrectCredentialsException("账户或密码错误");
        }

        if (authInfo.getStatus() == 1) {
            throw new DisabledAccountException("账户被冻结");
        }

        return new SimpleAuthenticationInfo(authInfo, password, getName());
    }
}
